package com.lepu.app.fun.chat.business.album;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.eyzhs.app.R;
import com.lepu.app.fun.chat.controller.base.AbsBaseFragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import common.db.Constants;
import common.db.alummage.ImageItem;
import view.AnimationImageView;
import view.OnZoomImageClickCallBack;

import static com.nostra13.universalimageloader.core.assist.ImageScaleType.EXACTLY;

/**
 * Created by chuanyhu on 2014/8/2.
 */


public class PhotoPreviewFragment extends AbsBaseFragment {

    private DisplayImageOptions options;
    private ViewPager pager;
    private View photoview;
    private TextView tv_size;
    private ImagePagerAdapter pagerAdapter;

    private int maxAlowSelectedNumber;
    private int currentPosition = 0; //默认pagerposiotn位置
    private int previousPagerPosition = 0;

    private boolean pagerStateChanged = false;
    private ImageButton imgBtnOk;

    private List<ImageItem> imageList;
    private List<ImageItem> selectedImageList;
    private static final String STATE_POSITION = "STATE_POSITION";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setoption();
        Bundle bundle = this.getArguments();
        imageList = (ArrayList) bundle.getSerializable(Constants.PhotoSelected_AllImages);
        selectedImageList = (ArrayList) bundle.getSerializable(Constants.PhotoSelected_SelectedImages);
        currentPosition = bundle.getInt(Constants.PhotoSelected_CurrentPosition, 0);
        maxAlowSelectedNumber = bundle.getInt(Constants.PhotoSelected_MaxAllowSelectNumber);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_POSITION, pager.getCurrentItem());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            currentPosition = savedInstanceState.getInt(STATE_POSITION);
        }
        photoview = inflater.inflate(R.layout.chat_fragment_photo_preview, null);
        pager = (ViewPager) photoview.findViewById(R.id.viewpager_photo);
        imgBtnOk = (ImageButton) photoview.findViewById(R.id.item_iv_ok);
        pager.setPageMargin(20);
        pagerAdapter = new ImagePagerAdapter(imageList);
        pager.setAdapter(pagerAdapter);
        pager.setCurrentItem(currentPosition);
        pager.setOffscreenPageLimit(3);
        pager.setOnPageChangeListener(new OnPageChangeListenerImpl());
        ImageButton item_iv_back = (ImageButton) photoview.findViewById(R.id.item_iv_back);
        ImageButton item_iv_ok = (ImageButton) photoview.findViewById(R.id.item_iv_ok);
        tv_size = (TextView) photoview.findViewById(R.id.tv_size);
        Button item_bottom = (Button) photoview.findViewById(R.id.item_bottom);
        //提交上传
        item_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedImageList.size() == 0) {
                    Toast.makeText(getActivity(), R.string.onlyselect, Toast.LENGTH_SHORT).show();
                    return;
                }
                Bundle param = new Bundle();
                param.putSerializable(Constants.PhotoSelected_SelectedImages, (ArrayList) selectedImageList);
                performGoAction("gotoEmbellish", param);
            }
        });
        if (imageList.get(pager.getCurrentItem()).isSelected) {
            imgBtnOk.setImageResource(R.drawable.chat_icon_data_select);
        }
        updateSelectedNumber(selectedImageList.size());
        item_iv_ok.setOnClickListener(btnOkClick);
        item_iv_back.setOnClickListener(new BackButtonClickListener());//返回

        return photoview;
    }

    private class ImagePagerAdapter extends PagerAdapter {

        private List<ImageItem> imageList;
        private LayoutInflater inflater;

        private Map<Integer, AnimationImageView> imageViewMap = new HashMap();

        ImagePagerAdapter(List<ImageItem> imageList) {
            this.imageList = imageList;
            inflater = getActivity().getLayoutInflater();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            imageViewMap.remove(position);
        }

        @Override
        public int getCount() {
            return imageList.size();
        }

        @Override
        public Object instantiateItem(ViewGroup view, final int position) {
            View imageLayout = inflater.inflate(R.layout.chat_fragment_item_pager_preview, view, false);
            AnimationImageView imageView = (AnimationImageView) imageLayout.findViewById(R.id.imgview_preview);
            final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
            //初始化状态
            String imagePath = "file://" + imageList.get(position).imagePath;
            ImageLoader.getInstance().displayImage(imagePath, imageView, options,
                    new ImageLoadingListener(spinner, imageView, position),
                    new SimpleImageLoadingProgressListener(spinner) {
                        @Override
                        public void onProgressUpdate(String imageUri, View view, int current, int total) {
                            spinner.setVisibility(View.VISIBLE);
                            spinner.setProgress(Math.round(100.0f * current / total));
                            if (current == total) {
                                spinner.setVisibility(View.INVISIBLE);
                            }
                        }

                    });

            imageViewMap.put(position, imageView);
            view.addView(imageLayout, 0);
            return imageLayout;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        public ImageView getImageView(int position) {
            return imageViewMap.get(position);
        }

    }

    /**
     * 更新选择数量
     *
     * @param number
     */
    void updateSelectedNumber(int number) {
        if (selectedImageList.size() != 0) {
            tv_size.setVisibility(View.VISIBLE);
            tv_size.setText(String.valueOf(number));
        } else {
            tv_size.setVisibility(View.GONE);
        }

    }


    class BackButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            System.out.println("-----点击了--------");
            Bundle retParam = new Bundle();
            retParam.putSerializable(Constants.PhotoSelected_SelectedImages, (ArrayList) selectedImageList);
            performBack(retParam);
        }
    }


    View.OnClickListener btnOkClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ImageView item_iv_ok = (ImageView) v;
            ImageItem item = imageList.get(pager.getCurrentItem());

            if (item.isSelected) {
                item.isSelected = false;
                item_iv_ok.setImageResource(R.drawable.chat_icon_data_unselect);
                selectedImageList.remove(item);
            } else if (!item.isSelected) {
                if (selectedImageList.size() >= maxAlowSelectedNumber) {
                    //提示超过允许选择的数
                    Toast.makeText(getActivity(), getResources().getString(R.string.max3PictureTip), Toast.LENGTH_SHORT).show();
                    return;
                }
                item.isSelected = true;
                item_iv_ok.setImageResource(R.drawable.chat_icon_data_select);
                selectedImageList.add(item);
            }
            //刷新选中数
            updateSelectedNumber(selectedImageList.size());
        }
    };

    class OnPageChangeListenerImpl implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            int newPosition = position % imageList.size();
            currentPosition = newPosition;
            pagerStateChanged = true;//
            ImageItem item = imageList.get(position);

            if (item.isSelected) {
                imgBtnOk.setImageResource(R.drawable.chat_icon_data_select);
            } else {
                imgBtnOk.setImageResource(R.drawable.chat_icon_data_unselect);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            //state三种状态1的时候默示正在滑动，arg0==2的时候默示滑动完毕了，arg0==0的时候默示什么都没做。
            //翻页后图片的缩放回到最初状态，必须要在状态0且onPageSelected调用后（页发生改变）后进行，在状态2进行会看到图片回到原始大小的过程，不友好
            switch (state) {
                case 0://
                    if (pagerStateChanged) {
                        AnimationImageView preImageView = (AnimationImageView) pagerAdapter.getImageView(previousPagerPosition);
                        if (null == preImageView) {
                            return;
                        }
                        Matrix matrix = new Matrix();
                        matrix.set(preImageView.getImageMatrix());
                        float[] values = new float[9];
                        matrix.getValues(values);
                        float viewwidth = preImageView.getWidth();
                        float viewheight = preImageView.getHeight();
                        float imagewidth = preImageView.getDrawable().getBounds().width();
                        float imageheight = preImageView.getDrawable().getBounds().height();

                        float ratiox = viewwidth / imagewidth;
                        float ratioy = viewheight / imageheight;
                        float minratio = ratiox < ratioy ? ratiox : ratioy;
                        float transx, transy;
                        if (ratiox < ratioy) {
                            transx = 0;
                            transy = (viewheight - ratiox * imageheight) / 2;
                        } else {
                            transx = (viewwidth - ratioy * imagewidth) / 2;
                            transy = 0;
                        }
                        values[0] = values[4] = minratio;
                        values[2] = transx;
                        values[5] = transy;
                        matrix.setValues(values);
                        preImageView.setImageMatrix(matrix);
                        pagerStateChanged = false;
                    }
                    break;
                case 2:
                    previousPagerPosition = currentPosition;
                    break;
                default:
                    break;
            }
        }
    }

    public class ImageLoadingListener extends SimpleImageLoadingListener {
        private ProgressBar spinner;
        private AnimationImageView imageView;
        private int position;

        ImageLoadingListener(final ProgressBar spinner, ImageView imageview, int position) {
            this.spinner = spinner;
            this.imageView = (AnimationImageView) imageview;
            this.position = position;
        }

        @Override
        public void onLoadingStarted(String imageUri, View view) {
            spinner.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            String message = null;
            switch (failReason.getType()) {
                case IO_ERROR:
                    message = "Input/Output error";
                    break;
                case DECODING_ERROR:
                    message = "Image can't be decoded";
                    break;
                case NETWORK_DENIED:
                    message = "Downloads are denied";
                    break;
                case OUT_OF_MEMORY:
                    message = "Out Of Memory error";
                    break;
                case UNKNOWN:
                    message = "Unknown error";
                    break;
            }
            spinner.setVisibility(View.GONE);
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            spinner.setVisibility(View.GONE);
            //by chengl
            imageView.setClickCallBack(new OnZoomImageClickCallBack() {
                @Override
                public void OnLongClickResponse(PointF point) {
                }

                public void OnDoubleClickResponse(PointF point) {
                    float magfactor = 1.6f;
                    float float_epsilon = 1e-3f;
                    float viewwidth = imageView.getWidth();
                    float viewheight = imageView.getHeight();
                    float imagewidth = imageView.getDrawable().getBounds().width();
                    float imageheight = imageView.getDrawable().getBounds().height();

                    Matrix matrix = new Matrix();
                    matrix.set(imageView.getImageMatrix());
                    float[] values = new float[9];
                    matrix.getValues(values);

                    float ratiox = viewwidth / imagewidth;
                    float ratioy = viewheight / imageheight;
                    float minratio = ratiox < ratioy ? ratiox : ratioy;
                    float transx, transy;
                    //回原图
                    if (values[0] > (minratio + float_epsilon)) {
                        if (ratiox < ratioy) {
                            transx = 0;
                            transy = (viewheight - ratiox * imageheight) / 2;
                        } else {
                            transx = (viewwidth - ratioy * imagewidth) / 2;
                            transy = 0;
                        }
                        values[0] = values[4] = minratio;
                        values[2] = transx;
                        values[5] = transy;
                        matrix.setValues(values);
                        imageView.EnableAnimation(imageView.getImageMatrix(), matrix, 200);
                    } else {//放大
                        matrix.postScale(magfactor, magfactor, point.x, point.y);
                        imageView.EnableAnimation(imageView.getImageMatrix(), matrix, 200);
                    }
                }

                public void OnSingleTapConfirmed(PointF point) {
                    getActivity().finish();
                }
            });
        }
    }

    public class SimpleImageLoadingProgressListener implements ImageLoadingProgressListener {
        private ProgressBar spinner;
        private boolean firstDo = true;

        SimpleImageLoadingProgressListener(final ProgressBar spinner) {
            this.spinner = spinner;
        }

        @Override
        public void onProgressUpdate(String imageUri, View view, int current, int total) {
            spinner.setVisibility(View.VISIBLE);
            spinner.setProgress(Math.round(100.0f * current / total));
            if (current == total) {
                spinner.setVisibility(View.INVISIBLE);
            }
        }
    }

    /**
     * 加载效果
     */
    private void setoption() {
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.chat_empty_photo)
                .showImageOnFail(R.drawable.chat_empty_photo)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true)
                .imageScaleType(EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new FadeInBitmapDisplayer(300))
                .build();
    }
}




